//
//  BluetoothAdapter.m
//  blocklyios
//
//  Created by steward on 2018/11/5.
//  Copyright © 2018 szltech. All rights reserved.
//

#import "BluetoothAdapter.h"
#import "BluetoothItemCell.h"
#import "BabyBluetooth.h"

@interface BluetoothAdapter()
@property (strong, nonatomic) NSMutableArray<CBPeripheral *> *devices;
@property (weak, nonatomic) UITableView *tableView;

@end

@implementation BluetoothAdapter

- (instancetype)initWithTableView: (UITableView *)tableView {
    self = [super init];
    if (self) {
        self.devices = [NSMutableArray.alloc init];
        self.tableView = tableView;
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
    }
    return self;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.listener(indexPath.row);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CBPeripheral * peripheral = self.devices[indexPath.row];
    static NSString *id = @"BluetoothItemCell";
    BluetoothItemCell *cell = [tableView dequeueReusableCellWithIdentifier:id];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([BluetoothItemCell class]) owner:self options:nil] firstObject];
    }
    [cell initCell:peripheral];
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.devices.count;
}

- (void)setItems: (NSMutableArray *)items {
    [self.devices removeAllObjects];
    [self.devices addObjectsFromArray:items];
    [self.tableView reloadData];
}

- (void)addItems: (NSMutableArray *)items {
    [self.devices addObjectsFromArray:items];
    [self.tableView reloadData];
}

-(NSArray<CBPeripheral *> *)getItems {
    return self.devices;
}
@end
